package com.example.testp;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View {
	Bitmap bmp;
	float x,y;
	float[] rx=new float[5],ry=new float[5];float rw;
	public GameView(Context context) {
		super(context);
		x=50;y=50;
		rw=100;
		rx[0]=300;ry[0]=700;
		rx[1]=180;ry[1]=760;
		rx[2]=420;ry[2]=760;
		rx[3]=300;ry[3]=820;
		Resources res=context.getResources();
		bmp=BitmapFactory.decodeResource(res, R.drawable.battlecity);
		setFocusable(true);
		// TODO Auto-generated constructor stub
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}
	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		super.onDraw(canvas);
		canvas.drawText("坦克大战", x, y, new Paint());
		canvas.drawBitmap(bmp,x,y+50,new Paint());
		for(int i=0;i<4;i++){
			canvas.drawRect(rx[i], ry[i], rx[i]+rw, ry[i]+rw,new Paint());
		}
	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		switch(keyCode){
		case KeyEvent.KEYCODE_DPAD_UP:
			y-=10;break;
		case KeyEvent.KEYCODE_DPAD_DOWN:
			y+=10;break;
		case KeyEvent.KEYCODE_DPAD_LEFT:
			x-=10;break;
		case KeyEvent.KEYCODE_DPAD_RIGHT:
			x+=10;break;
		}
		postInvalidate();
		return super.onKeyDown(keyCode, event);
	}
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// TODO Auto-generated method stub
		if(event.getAction()==MotionEvent.ACTION_DOWN){
			float ax=event.getX();
			float ay=event.getY();
			if(ax>rx[0]&&ax<rx[0]+rw&&ay>ry[0]&&ay<ry[0]+rw){
				y-=30;
			}
			if(ax>rx[1]&&ax<rx[1]+rw&&ay>ry[1]&&ay<ry[1]+rw){
				x-=30;
			}
			if(ax>rx[2]&&ax<rx[2]+rw&&ay>ry[2]&&ay<ry[2]+rw){
				x+=30;
			}
			if(ax>rx[3]&&ax<rx[3]+rw&&ay>ry[3]&&ay<ry[3]+rw){
				y+=30;
			}
			postInvalidate();
		}
		/*else if(event.getAction()==MotionEvent.ACTION_MOVE){
			float ax=event.getX();
			float ay=event.getY();
			x=ax;y=ay;
			postInvalidate();
		}*/
		//return super.onTouchEvent(event);
		 return true;
	}

}
